import json

from django.core.cache.backends import redis
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from utils.goods import get_categories, get_breadcrumb, get_goods_specs

# Create your views here.


class IndexView(View):

    def get(self,request):

        """
        首页的数据分为2部分
        1部分是 商品分类数据
        2部分是 广告数据

        """
        # 1.商品分类数据

        categories = get_categories()
        # 2.广告数据
        contents = {}

        from contents.models import ContentCategory
        content_categories = ContentCategory.objects.all()
        for cat in content_categories:
            contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

        # 我们的首页 后边会讲解页面静态化
        # 我们把数据 传递 给 模板
        context = {
            'categories': categories,
            'contents': contents,
        }
        # 模板使用比较少，以后大家到公司 自然就会了
        return render(request, 'index.html', context)




from goods.models import GoodsCategory, SKU
class ListView(View):

    def get(self, request, category_id):

        # 排序字段
        ordering = request.GET.get('ordering')

        # 每页多少条数据
        page_size = request.GET.get('page_size')

        # 获取指定页数据
        page = request.GET.get('page')

        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code': 400})

        # 面包屑
        breadcrumb = get_breadcrumb(category)

        skus = SKU.objects.filter(category=category).order_by(ordering)

        # 分页
        from django.core.paginator import Paginator
        # object_list, per_page
        # object_list   列表数据
        # per_page      每页多少条数据
        paginator = Paginator(skus, per_page=page_size)


        # 获取指定页码的数据
        page_skus = paginator.page(page)

        sku_list = []
        # 将对象转换为字典数据
        for sku in page_skus.object_list:
            sku_list.append({
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image.url
            })

        # 获取总页码
        total_num = paginator.num_pages

        # 6.返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'list': sku_list, 'count': total_num, 'breadcrumb': breadcrumb})




# 热销

class HotView(View):

    def get(self, request, category_id):

        hot_goods = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-price')[:2]


        # 序列化
        hotgoods_list = []
        for sku in hot_goods:
            hotgoods_list.append(
                {
                    'id': sku.id,
                    'default_image_url': sku.default_image.url,
                    'name': sku.name,
                    'price': sku.price
                }
            )

            return JsonResponse({'code': 0, 'hot_skus': hotgoods_list})
# '/hot/'+this.cat + '/'





from haystack.views import SearchView


class SKUSearchView(SearchView):
    # 重写create_response
    def create_response(self):

        context = self.get_context()        # 搜索结果
        sku_list = []
        for sku in context['page'].object_list:
            sku_list.append({
                'id': sku.object.id,
                'name': sku.object.name,
                'price': sku.object.price,
                'default_image_url': sku.object.default_image.url,
                'searchkey': context.get('query'),
                'page_size': context['page'].paginator.num_pages,
                'count': context['page'].paginator.count
            })
        return JsonResponse(sku_list, safe=False)


class DetailView(View):
    def get(self, request, sku_id):
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            pass
            # return JsonResponse({'code': 400, 'errmsg': 'The sku_id not exist'})

        categories = get_categories()
        breadcrumb = get_breadcrumb(sku.category)
        goods_specs = get_goods_specs(sku)


        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': goods_specs,
        }

        return render(request, 'detail.html', context)



# /detail/visit/<category_id>/
from goods.models import GoodsVisitCount
from datetime import date


class Category_VisitCount(View):

    def post(self, request, category_id):

        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '分类不存在'})
        today = date.today()

        try:
            visit_count = GoodsVisitCount.objects.get(category=category_id, date=today)
        except GoodsVisitCount.DoesNotExist:
            GoodsVisitCount.objects.create(category=category, count=1, date=today)

        else:
            visit_count.count += 1
            visit_count.save()
        return JsonResponse({'code': 0, 'errmsg': 'ok'})




















class Goods(View):
    def get(self, request, ):

        JsonResponse({})